<template>
  <div class="agent-center">
    <div class="agent-layout">
      <aside class="agent-sidebar">
        <div class="sidebar-toolbar">
          <el-button type="primary" :icon="Plus" @click="handleCreateAgent">
            新建智能体
          </el-button>
          <el-dropdown trigger="click">
            <span class="el-dropdown-link">
              <el-button text :icon="MoreFilled"></el-button>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item :icon="Upload" @click="handleImportAgents">
                  导入配置
                </el-dropdown-item>
                <el-dropdown-item :icon="Download" @click="handleExportAgents">
                  导出全部
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
        <el-input
          v-model="searchKeyword"
          placeholder="搜索智能体名称、标签..."
          clearable
          :prefix-icon="Search"
          class="sidebar-search"
        />
        <el-select
          v-model="statusFilter"
          placeholder="状态筛选"
          clearable
          class="sidebar-filter"
        >
          <el-option label="全部状态" value="all" />
          <el-option label="已发布" value="published" />
          <el-option label="草稿" value="draft" />
        </el-select>
        <el-select
          v-model="tagFilter"
          placeholder="标签筛选"
          clearable
          filterable
          class="sidebar-filter"
        >
          <el-option
            v-for="tag in allTags"
            :key="tag"
            :label="tag"
            :value="tag"
          />
        </el-select>
        <el-scrollbar class="sidebar-list">
          <div
            v-for="agent in filteredAgents"
            :key="agent.id"
            :class="['agent-list-item', { active: agent.id === activeAgentId }]"
            @click="handleSelectAgent(agent.id)"
          >
            <div class="item-header">
              <div class="item-title">
                <el-avatar
                  v-if="agent.avatar"
                  :src="agent.avatar"
                  size="small"
                />
                <el-avatar v-else size="small" :icon="UserFilled" />
                <span class="name">{{ agent.name }}</span>
                <el-tag
                  size="small"
                  :type="agent.status === 'published' ? 'success' : 'info'"
                >
                  {{ agent.status === 'published' ? '已发布' : '草稿' }}
                </el-tag>
              </div>
              <el-dropdown trigger="click">
                <span class="el-dropdown-link">
                  <el-icon><MoreFilled /></el-icon>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item :icon="Check" @click.stop="handleSelectAgent(agent.id)">
                      设为当前
                    </el-dropdown-item>
                    <el-dropdown-item :icon="CopyDocument" @click.stop="handleCloneAgent(agent.id)">
                      复制
                    </el-dropdown-item>
                    <el-dropdown-item :icon="Download" @click.stop="handleExportAgents([agent.id])">
                      导出
                    </el-dropdown-item>
                    <el-dropdown-item
                      :icon="Delete"
                      divided
                      @click.stop="handleDeleteAgent(agent.id)"
                    >
                      删除
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
            <div class="item-description">
              {{ agent.description || '未填写描述' }}
            </div>
            <div class="item-tags">
              <el-tag
                v-for="tag in agent.tags"
                :key="tag"
                effect="plain"
                size="small"
              >
                {{ tag }}
              </el-tag>
            </div>
            <div class="item-footer">
              <span class="timestamp">
                更新于 {{ formatTime(agent.updatedAt) }}
              </span>
              <el-tag v-if="agent.id === activeAgentId" size="small" type="primary">
                当前使用
              </el-tag>
            </div>
          </div>
          <el-empty
            v-if="filteredAgents.length === 0"
            description="暂无智能体"
            class="sidebar-empty"
          />
        </el-scrollbar>
      </aside>

      <section class="agent-main" v-if="editableAgent.id">
        <header class="agent-main-header">
          <div>
            <h2>{{ editableAgent.name || '未命名智能体' }}</h2>
            <p>{{ editableAgent.description || '为智能体补充描述，有助于团队理解用途。' }}</p>
          </div>
          <div class="header-actions">
            <el-button
              type="primary"
              :icon="Check"
              @click="handleSaveAgent"
              :disabled="!isDirty"
            >
              保存
            </el-button>
            <el-button
              type="success"
              plain
              :icon="CollectionTag"
              @click="handlePublishAgent"
            >
              发布
            </el-button>
            <el-button
              type="warning"
              plain
              :icon="StarFilled"
              @click="handleSelectAgent(editableAgent.id)"
            >
              设为当前
            </el-button>
          </div>
        </header>

        <div class="agent-main-body">
          <div class="agent-form-panel">
            <el-tabs v-model="activeTab" class="agent-tabs">
              <el-tab-pane label="基础信息" name="basic">
                <el-form
                  ref="basicFormRef"
                  label-width="120px"
                  :model="editableAgent"
                >
                  <el-row :gutter="16">
                    <el-col :span="12">
                      <el-form-item label="名称" prop="name" required>
                        <el-input v-model="editableAgent.name" maxlength="60" show-word-limit />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="标签">
                        <el-select
                          v-model="editableAgent.tags"
                          multiple
                          filterable
                          allow-create
                          default-first-option
                          placeholder="添加或创建标签"
                        >
                          <el-option
                            v-for="tag in allTags"
                            :key="tag"
                            :label="tag"
                            :value="tag"
                          />
                        </el-select>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="16">
                    <el-col :span="12">
                      <el-form-item label="头像">
                        <el-input
                          v-model="editableAgent.avatar"
                          placeholder="支持网络图片 URL"
                          clearable
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="状态">
                        <el-tag
                          :type="editableAgent.status === 'published' ? 'success' : 'info'"
                        >
                          {{ editableAgent.status === 'published' ? '已发布' : '草稿' }}
                        </el-tag>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-form-item label="简介">
                    <el-input
                      type="textarea"
                      v-model="editableAgent.description"
                      :rows="3"
                      maxlength="150"
                      show-word-limit
                      placeholder="简要说明智能体负责的场景与价值..."
                    />
                  </el-form-item>
                  <el-divider content-position="left">系统提示词与对话策略</el-divider>
                  <el-form-item label="System Prompt">
                    <el-input
                      type="textarea"
                      v-model="editableAgent.prompt.system"
                      :rows="4"
                      placeholder="定义智能体的核心角色、背景与职责"
                    />
                  </el-form-item>
                  <el-form-item label="风格指引">
                    <el-input
                      type="textarea"
                      v-model="editableAgent.prompt.styleGuide"
                      :rows="3"
                      placeholder="约束语言风格、结构、术语等"
                    />
                  </el-form-item>
                  <el-form-item label="拒答策略">
                    <el-input
                      type="textarea"
                      v-model="editableAgent.prompt.refusalPolicy"
                      :rows="3"
                      placeholder="说明不可回答场景与回应模板"
                    />
                  </el-form-item>
                  <el-form-item label="开场白">
                    <el-input
                      type="textarea"
                      v-model="editableAgent.prompt.openingMessage"
                      :rows="2"
                      placeholder="进入对话时的欢迎语"
                    />
                  </el-form-item>
                  <el-form-item label="记忆策略">
                    <el-radio-group v-model="editableAgent.prompt.memoryStrategy">
                      <el-radio-button label="off">关闭记忆</el-radio-button>
                      <el-radio-button label="window">固定窗口</el-radio-button>
                      <el-radio-button label="summary">总结压缩</el-radio-button>
                    </el-radio-group>
                  </el-form-item>
                  <el-divider content-position="left">体验开关</el-divider>
                  <el-row :gutter="16">
                    <el-col :span="12">
                      <el-form-item label="语音输入">
                        <el-switch v-model="editableAgent.featureToggles.enableVoiceInput" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="Markdown 渲染">
                        <el-switch v-model="editableAgent.featureToggles.enableMarkdown" />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="16">
                    <el-col :span="12">
                      <el-form-item label="代码高亮">
                        <el-switch v-model="editableAgent.featureToggles.enableCodeHighlight" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="显示推理过程">
                        <el-switch v-model="editableAgent.featureToggles.enableReasoning" />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="12">
                      <el-form-item label="自动滚动">
                        <el-switch v-model="editableAgent.featureToggles.autoScroll" />
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form>
              </el-tab-pane>

              <el-tab-pane label="模型与参数" name="model">
                <el-form label-width="150px">
                  <el-row :gutter="16">
                    <el-col :span="12">
                      <el-form-item label="模型提供方">
                        <el-select v-model="editableAgent.llm.provider" placeholder="选择厂商">
                          <el-option label="OpenAI" value="openai" />
                          <el-option label="Azure OpenAI" value="azure" />
                          <el-option label="Anthropic" value="anthropic" />
                          <el-option label="百度千帆" value="baidu-qianfan" />
                          <el-option label="阿里通义" value="ali-qwen" />
                          <el-option label="自定义" value="custom" />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="模型名称">
                        <el-input v-model="editableAgent.llm.model" placeholder="如 gpt-4.1-mini" />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="16">
                    <el-col :span="12">
                      <el-form-item label="调用地址">
                        <el-input v-model="editableAgent.llm.endpoint" placeholder="HTTP / WebSocket 地址" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="SSE 地址">
                        <el-input v-model="editableAgent.llm.sseUrl" placeholder="流式响应地址" />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="16">
                    <el-col :span="8">
                      <el-form-item label="温度 (Temperature)">
                        <el-slider
                          v-model="editableAgent.llm.temperature"
                          :min="0"
                          :max="2"
                          :step="0.1"
                          show-input
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="Top P">
                        <el-slider
                          v-model="editableAgent.llm.top_p"
                          :min="0"
                          :max="1"
                          :step="0.01"
                          show-input
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="Top K">
                        <el-input-number
                          v-model="editableAgent.llm.top_k"
                          :min="0"
                          :max="100"
                          :step="5"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="16">
                    <el-col :span="8">
                      <el-form-item label="频率惩罚">
                        <el-slider
                          v-model="editableAgent.llm.frequency_penalty"
                          :min="-2"
                          :max="2"
                          :step="0.1"
                          show-input
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="存在惩罚">
                        <el-slider
                          v-model="editableAgent.llm.presence_penalty"
                          :min="-2"
                          :max="2"
                          :step="0.1"
                          show-input
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="最大 Tokens">
                        <el-input-number
                          v-model="editableAgent.llm.max_tokens"
                          :min="128"
                          :max="8000"
                          :step="64"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-form-item label="响应格式">
                    <el-select v-model="editableAgent.llm.response_format" placeholder="选择格式">
                      <el-option label="自动" value="auto" />
                      <el-option label="JSON" value="json_object" />
                      <el-option label="文本" value="text" />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="停止词">
                    <el-select
                      v-model="editableAgent.llm.stop"
                      multiple
                      filterable
                      allow-create
                      default-first-option
                      placeholder="输入停止词后回车创建"
                    />
                  </el-form-item>
                </el-form>
              </el-tab-pane>

              <el-tab-pane label="上下文与记忆" name="context">
                <el-form label-width="150px">
                  <el-form-item label="启用记忆">
                    <el-switch v-model="editableAgent.context.enableMemory" />
                  </el-form-item>
                  <el-form-item label="记忆方式">
                    <el-radio-group v-model="editableAgent.context.memoryType">
                      <el-radio label="summary">对话总结</el-radio>
                      <el-radio label="full">完整保留</el-radio>
                      <el-radio label="vector">向量检索</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-row :gutter="16">
                    <el-col :span="12">
                      <el-form-item label="上下文窗口">
                        <el-input-number
                          v-model="editableAgent.context.conversationWindow"
                          :min="0"
                          :max="100"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="总结频率">
                        <el-input-number
                          v-model="editableAgent.context.summaryInterval"
                          :min="1"
                          :max="20"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-form-item label="记忆保留时长">
                    <el-select v-model="editableAgent.context.memoryRetention">
                      <el-option label="1天" value="1d" />
                      <el-option label="7天" value="7d" />
                      <el-option label="30天" value="30d" />
                      <el-option label="永久" value="permanent" />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="遗忘规则">
                    <el-select
                      v-model="editableAgent.context.forgetRules"
                      multiple
                      filterable
                      allow-create
                      default-first-option
                      placeholder="添加关键词或规则"
                    />
                  </el-form-item>
                </el-form>
              </el-tab-pane>

              <el-tab-pane label="能力与工具" name="capabilities">
                <el-form label-width="150px">
                  <el-form-item label="可调用工具">
                    <el-select
                      v-model="editableAgent.capabilities.tools"
                      multiple
                      filterable
                      allow-create
                      default-first-option
                      placeholder="如：web_search, erp_query"
                    />
                  </el-form-item>
                  <el-form-item label="知识库授权">
                    <el-select
                      v-model="editableAgent.capabilities.knowledgeBases"
                      multiple
                      filterable
                      allow-create
                      default-first-option
                      placeholder="如：合同模板库"
                    />
                  </el-form-item>
                  <el-form-item label="工作流">
                    <el-select
                      v-model="editableAgent.capabilities.workflows"
                      multiple
                      filterable
                      allow-create
                      default-first-option
                      placeholder="如：审批流程v2"
                    />
                  </el-form-item>
                  <el-row :gutter="16">
                    <el-col :span="8">
                      <el-form-item label="允许文件上传">
                        <el-switch v-model="editableAgent.capabilities.allowFileUpload" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="允许联网搜索">
                        <el-switch v-model="editableAgent.capabilities.allowWebAccess" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="允许插件执行">
                        <el-switch v-model="editableAgent.capabilities.allowPluginExecution" />
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form>
              </el-tab-pane>

              <el-tab-pane label="合规与限额" name="compliance">
                <el-form label-width="150px">
                  <el-form-item label="敏感词库">
                    <el-input
                      v-model="editableAgent.compliance.sensitiveWordListId"
                      placeholder="填写敏感词库编号或名称"
                    />
                  </el-form-item>
                  <el-form-item label="审计级别">
                    <el-select v-model="editableAgent.compliance.auditLevel">
                      <el-option label="标准" value="standard" />
                      <el-option label="严格" value="strict" />
                      <el-option label="宽松" value="relaxed" />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="自动脱敏">
                    <el-switch v-model="editableAgent.compliance.autoRedact" />
                  </el-form-item>
                  <el-form-item label="免责声明">
                    <el-input
                      type="textarea"
                      v-model="editableAgent.compliance.disclaimers"
                      :rows="3"
                    />
                  </el-form-item>
                  <el-divider content-position="left">调用限额</el-divider>
                  <el-row :gutter="16">
                    <el-col :span="12">
                      <el-form-item label="每日总请求">
                        <el-input-number
                          v-model="editableAgent.limits.dailyRequests"
                          :min="0"
                          :max="100000"
                          :step="50"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="单用户请求">
                        <el-input-number
                          v-model="editableAgent.limits.perUserRequests"
                          :min="0"
                          :max="10000"
                          :step="10"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="16">
                    <el-col :span="12">
                      <el-form-item label="Token 预算">
                        <el-input-number
                          v-model="editableAgent.limits.tokenBudget"
                          :min="0"
                          :max="1000000"
                          :step="1000"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="并发限制">
                        <el-input-number
                          v-model="editableAgent.limits.concurrency"
                          :min="1"
                          :max="100"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-form-item label="告警阈值">
                    <el-slider
                      v-model="editableAgent.limits.alertThreshold"
                      :min="0"
                      :max="1"
                      :step="0.05"
                      show-input
                    />
                  </el-form-item>
                </el-form>
              </el-tab-pane>

              <el-tab-pane label="监控与版本" name="monitoring">
                <el-row :gutter="16">
                  <el-col :span="14">
                    <el-card shadow="never" class="monitor-card">
                      <template #header>
                        <div class="card-header">
                          <span>监控告警</span>
                        </div>
                      </template>
                      <el-form label-width="140px">
                        <el-form-item label="启用性能监控">
                          <el-switch v-model="editableAgent.monitoring.enableMetrics" />
                        </el-form-item>
                        <el-form-item label="延迟告警阈值 (ms)">
                          <el-input-number
                            v-model="editableAgent.monitoring.latencyThreshold"
                            :min="0"
                            :max="60000"
                            :step="500"
                          />
                        </el-form-item>
                        <el-form-item label="错误率阈值">
                          <el-slider
                            v-model="editableAgent.monitoring.errorAlertThreshold"
                            :min="0"
                            :max="1"
                            :step="0.01"
                            show-input
                          />
                        </el-form-item>
                        <el-form-item label="通知邮箱">
                          <el-select
                            v-model="editableAgent.monitoring.notifyEmails"
                            multiple
                            filterable
                            allow-create
                            default-first-option
                            placeholder="输入邮箱后回车"
                          />
                        </el-form-item>
                      </el-form>
                    </el-card>
                  </el-col>
                  <el-col :span="10">
                    <el-card shadow="never" class="monitor-card">
                      <template #header>
                        <div class="card-header">
                          <span>版本历史</span>
                        </div>
                      </template>
                      <el-timeline class="version-timeline">
                        <el-timeline-item
                          v-for="history in editableAgent.version?.history"
                          :key="history.id"
                          :timestamp="formatTime(history.timestamp)"
                          :type="history.type === 'publish' ? 'success' : 'info'"
                        >
                          <div class="timeline-item">
                            <div class="title">
                              v{{ history.version }} · {{ mapHistoryType(history.type) }}
                            </div>
                            <div class="note">{{ history.note || '未填写说明' }}</div>
                            <el-button
                              size="small"
                              type="primary"
                              text
                              :icon="Refresh"
                              @click="handleRestoreVersion(history.id)"
                            >
                              回滚
                            </el-button>
                          </div>
                        </el-timeline-item>
                        <div v-if="!(editableAgent.version?.history?.length)">
                          暂无版本记录
                        </div>
                      </el-timeline>
                    </el-card>
                  </el-col>
                </el-row>
              </el-tab-pane>
            </el-tabs>
          </div>

          <aside class="agent-preview-panel">
            <el-card class="preview-card" shadow="never">
              <template #header>
                <div class="card-header">
                  <span>对话预览</span>
                  <el-tag size="small">根据当前配置实时更新</el-tag>
                </div>
              </template>
              <div class="preview-section">
                <h4>开场白</h4>
                <p>{{ editableAgent.prompt.openingMessage || '未设置开场白' }}</p>
              </div>
              <div class="preview-section">
                <h4>角色设定</h4>
                <p>{{ editableAgent.prompt.system || '未设置角色设定' }}</p>
              </div>
              <div class="preview-section">
                <h4>示例响应</h4>
                <div class="preview-chat">
                  <div class="user-msg">
                    <strong>用户：</strong>
                    <p>{{ sampleUserQuestion }}</p>
                  </div>
                  <div class="assistant-msg">
                    <strong>智能体：</strong>
                    <p>{{ previewResponse }}</p>
                  </div>
                </div>
              </div>
              <div class="preview-section">
                <h4>启用工具</h4>
                <el-tag
                  v-for="tool in editableAgent.capabilities.tools"
                  :key="tool"
                  size="small"
                  >{{ tool }}</el-tag
                >
                <span v-if="!editableAgent.capabilities.tools?.length">-</span>
              </div>
              <div class="preview-section">
                <h4>注意事项</h4>
                <p>{{ editableAgent.prompt.refusalPolicy || '暂无特殊说明' }}</p>
              </div>
            </el-card>
          </aside>
        </div>
      </section>

      <section v-else class="agent-main empty">
        <el-empty description="请选择左侧智能体或新建配置" />
      </section>
    </div>
  </div>
</template>

<script setup>
import { computed, onMounted, reactive, ref, watch, toRaw } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Check,
  CollectionTag,
  CopyDocument,
  Delete,
  Download,
  MoreFilled,
  Plus,
  Refresh,
  Search,
  StarFilled,
  Upload,
  UserFilled
} from '@element-plus/icons-vue'
import { storeToRefs } from 'pinia'
import { useAgentStore } from '@/stores/agent'

const agentStore = useAgentStore()
const { agents, activeAgentId, activeAgent } = storeToRefs(agentStore)

const searchKeyword = ref('')
const tagFilter = ref(null)
const statusFilter = ref('all')
const activeTab = ref('basic')
const editableAgent = reactive({})
const isDirty = ref(false)
const lastSavedSnapshot = ref('')

const sampleUserQuestion = '我需要一份本季度销售数据汇总，并分析主要波动原因。'

const allTags = computed(() => {
  const set = new Set()
  agents.value.forEach((agent) => {
    (agent.tags || []).forEach((tag) => set.add(tag))
  })
  return Array.from(set)
})

const filteredAgents = computed(() => {
  const keyword = searchKeyword.value?.trim().toLowerCase()
  return agents.value.filter((agent) => {
    const statusMatch =
      statusFilter.value === 'all' || agent.status === statusFilter.value
    const tagMatch = !tagFilter.value || agent.tags?.includes(tagFilter.value)
    const keywordMatch =
      !keyword ||
      agent.name?.toLowerCase().includes(keyword) ||
      agent.description?.toLowerCase().includes(keyword) ||
      agent.tags?.some((tag) => tag.toLowerCase().includes(keyword))
    return statusMatch && tagMatch && keywordMatch
  })
})

const deepClone = (value) => {
  const rawValue = toRaw(value)
  if (typeof structuredClone === 'function') {
    try {
      return structuredClone(rawValue)
    } catch (error) {
      console.warn('[AgentCenter] structuredClone 失败，改用兼容实现', error)
    }
  }
  const visited = new WeakMap()
  const cloneRecursive = (val) => {
    if (val === null || typeof val !== 'object') {
      return val
    }
    if (visited.has(val)) {
      return visited.get(val)
    }
    if (Array.isArray(val)) {
      const arr = []
      visited.set(val, arr)
      val.forEach((item) => {
        arr.push(cloneRecursive(item))
      })
      return arr
    }
    const obj = {}
    visited.set(val, obj)
    Object.keys(val).forEach((key) => {
      obj[key] = cloneRecursive(val[key])
    })
    return obj
  }
  return cloneRecursive(rawValue)
}

const applyEditableAgent = (agent) => {
  Object.keys(editableAgent).forEach((key) => {
    delete editableAgent[key]
  })
  if (!agent) return
  const clone = deepClone(agent)
  Object.assign(editableAgent, clone)
  lastSavedSnapshot.value = JSON.stringify(clone)
  isDirty.value = false
}

const previewResponse = computed(() => {
  const opening = editableAgent.prompt?.openingMessage || ''
  const style = editableAgent.prompt?.styleGuide || ''
  const tools = editableAgent.capabilities?.tools || []
  const toolSentence = tools.length ? `我可以调用 ${tools.join('、')} 等能力协助您。` : ''
  if (!opening && !style && !toolSentence) {
    return '我会按照默认配置回答您的问题。'
  }
  return `${opening}\n${style ? `风格要求：${style}` : ''}\n${toolSentence}`.trim()
})

const formatTime = (timestamp) => {
  if (!timestamp) return '未知'
  const date = new Date(timestamp)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(
    date.getDate()
  ).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(
    date.getMinutes()
  ).padStart(2, '0')}`
}

const mapHistoryType = (type) => {
  switch (type) {
    case 'create':
      return '创建'
    case 'publish':
      return '发布'
    case 'restore':
      return '回滚'
    case 'clone':
      return '复制'
    case 'import':
      return '导入'
    default:
      return '更新'
  }
}

watch(
  () => editableAgent,
  () => {
    const snapshot = JSON.stringify(editableAgent)
    isDirty.value = snapshot !== lastSavedSnapshot.value
  },
  { deep: true }
)

watch(
  activeAgent,
  (agent) => {
    if (agent) {
      applyEditableAgent(agent)
    }
  },
  { immediate: true }
)

onMounted(() => {
  agentStore.initialize()
  if (activeAgent.value) {
    applyEditableAgent(activeAgent.value)
  }
})

const handleSelectAgent = (agentId) => {
  agentStore.selectAgent(agentId)
}

const handleCreateAgent = () => {
  ElMessageBox.prompt('请输入智能体名称', '新建智能体', {
    confirmButtonText: '创建',
    cancelButtonText: '取消',
    inputPlaceholder: '例如：法务合同助手'
  })
    .then(({ value }) => {
      const name = value?.trim() || '未命名智能体'
      const agent = agentStore.createAgent({
        name,
        description: '',
        status: 'draft'
      })
      applyEditableAgent(agent)
      ElMessage.success('已创建新智能体')
    })
    .catch(() => {})
}

const handleSaveAgent = () => {
  if (!editableAgent.id) return
  try {
    const saved = agentStore.updateAgent(
      editableAgent.id,
      deepClone(editableAgent),
      {
        mergeStrategy: 'replace',
        note: '前端保存'
      }
    )
    if (saved) {
      applyEditableAgent(saved)
      ElMessage.success('智能体配置已保存')
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('保存失败')
  }
}

const handlePublishAgent = () => {
  if (!editableAgent.id) return
  ElMessageBox.prompt('填写本次发布说明（可选）', '发布新版本', {
    confirmButtonText: '发布',
    cancelButtonText: '取消',
    inputPlaceholder: '例如：优化拒答策略，新增审批流程触发',
    inputValue: '更新配置'
  })
    .then(({ value }) => {
      handleSaveAgent()
      const published = agentStore.publishAgent(
        editableAgent.id,
        value || '发布更新'
      )
      if (published) {
        applyEditableAgent(published)
        ElMessage.success('已发布新版本')
      }
    })
    .catch(() => {})
}

const handleDeleteAgent = (agentId) => {
  ElMessageBox.confirm('确认删除该智能体？操作不可恢复。', '删除智能体', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      agentStore.deleteAgent(agentId)
      ElMessage.success('已删除智能体')
    })
    .catch(() => {})
}

const handleCloneAgent = (agentId) => {
  const cloned = agentStore.cloneAgent(agentId)
  if (cloned) {
    applyEditableAgent(cloned)
    ElMessage.success('已复制智能体为草稿')
  }
}

const handleRestoreVersion = (historyId) => {
  if (!editableAgent.id) return
  ElMessageBox.confirm('确定回滚至该版本？当前未保存修改将丢失。', '回滚版本', {
    confirmButtonText: '回滚',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      const restored = agentStore.restoreVersion(
        editableAgent.id,
        historyId,
        '回滚版本'
      )
      if (restored) {
        applyEditableAgent(restored)
        ElMessage.success('已回滚至选择的版本')
      }
    })
    .catch(() => {})
}

const handleImportAgents = () => {
  ElMessageBox.prompt('粘贴导出的智能体 JSON 内容', '导入智能体', {
    inputType: 'textarea',
    confirmButtonText: '导入',
    cancelButtonText: '取消',
    inputPlaceholder: '粘贴 JSON 数组'
  })
    .then(({ value }) => {
      if (!value) return
      const count = agentStore.importAgents(value)
      ElMessage.success(`已导入 ${count} 个智能体`)
    })
    .catch(() => {})
}

const handleExportAgents = (agentIds = null) => {
  const json = agentStore.exportAgents(agentIds)
  const blob = new Blob([json], { type: 'application/json;charset=utf-8' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  const timestamp = new Date().toISOString().replace(/[:.]/g, '-')
  a.href = url
  a.download = `agents-${timestamp}.json`
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)
  ElMessage.success('导出文件已开始下载')
}
</script>

<style scoped lang="scss">
.agent-center {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.agent-layout {
  flex: 1;
  display: flex;
  min-height: 0;
}

.agent-sidebar {
  width: 320px;
  border-right: 1px solid #ebeef5;
  padding: 16px;
  display: flex;
  flex-direction: column;
  background: #fafafa;
}

.sidebar-toolbar {
  display: flex;
  gap: 8px;
  align-items: center;
  margin-bottom: 12px;
}

.sidebar-search,
.sidebar-filter {
  margin-bottom: 12px;
}

.sidebar-list {
  flex: 1;
  min-height: 0;
}

.agent-list-item {
  background: #fff;
  border: 1px solid transparent;
  border-radius: 10px;
  padding: 12px;
  margin-bottom: 12px;
  cursor: pointer;
  transition: all 0.2s;

  &:hover {
    border-color: var(--el-color-primary-light-5);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  }

  &.active {
    border-color: var(--el-color-primary);
    box-shadow: 0 6px 18px rgba(64, 158, 255, 0.15);
  }
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 6px;
}

.item-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #303133;
}

.item-description {
  font-size: 13px;
  color: #606266;
  margin-bottom: 8px;
  line-height: 1.4;
  min-height: 36px;
}

.item-tags {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
  margin-bottom: 8px;
}

.item-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #909399;
}

.timestamp {
  color: #a0a3a8;
}

.sidebar-empty {
  margin-top: 60px;
}

.agent-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-width: 0;
  background: #f6f7fb;
}

.agent-main.empty {
  align-items: center;
  justify-content: center;
}

.agent-main-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 20px 24px 12px;
  background: #fff;
  border-bottom: 1px solid #ebeef5;

  h2 {
    margin: 0;
    font-size: 22px;
    font-weight: 600;
    color: #1f2d3d;
  }

  p {
    margin-top: 6px;
    color: #606266;
    font-size: 13px;
  }
}

.header-actions {
  display: flex;
  gap: 10px;
}

.agent-main-body {
  flex: 1;
  display: flex;
  min-height: 0;
  overflow: hidden;
}

.agent-form-panel {
  flex: 1;
  padding: 20px 24px 24px;
  overflow-y: auto;
}

.agent-tabs {
  background: #fff;
  padding: 12px 16px;
  border-radius: 14px;
  box-shadow: 0 8px 24px rgba(31, 45, 61, 0.05);
}

.agent-preview-panel {
  width: 340px;
  padding: 20px;
  border-left: 1px solid #ebeef5;
  background: #fdfdfd;
  overflow-y: auto;
}

.preview-card {
  border-radius: 14px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
}

.preview-section {
  margin-bottom: 18px;

  h4 {
    font-size: 14px;
    color: #303133;
    margin-bottom: 6px;
  }

  p {
    font-size: 13px;
    color: #606266;
    line-height: 1.6;
  }
}

.preview-chat {
  background: #f5f7fa;
  border-radius: 10px;
  padding: 12px;
  font-size: 13px;
  color: #606266;
  display: flex;
  flex-direction: column;
  gap: 10px;

  .user-msg,
  .assistant-msg {
    line-height: 1.5;

    strong {
      color: #303133;
      display: block;
      margin-bottom: 4px;
    }
  }
}

.monitor-card {
  border-radius: 12px;
}

.version-timeline {
  max-height: 360px;
  overflow-y: auto;
}

.timeline-item {
  display: flex;
  flex-direction: column;
  gap: 4px;

  .title {
    font-weight: 600;
    color: #303133;
  }

  .note {
    font-size: 12px;
    color: #606266;
  }
}

@media (max-width: 1440px) {
  .agent-preview-panel {
    width: 300px;
  }
}

@media (max-width: 1200px) {
  .agent-layout {
    flex-direction: column;
  }

  .agent-sidebar {
    width: 100%;
    border-right: none;
    border-bottom: 1px solid #ebeef5;
    flex-direction: row;
    flex-wrap: wrap;
    gap: 12px;
  }

  .sidebar-toolbar {
    width: 100%;
  }

  .sidebar-search,
  .sidebar-filter,
  .sidebar-list {
    width: 100%;
  }

  .agent-main-body {
    flex-direction: column;
  }

  .agent-preview-panel {
    width: 100%;
    order: -1;
    border-left: none;
    border-top: 1px solid #ebeef5;
    display: none;
  }
}
</style>

